import React, {FunctionComponentElement, useContext, useState} from "react";
import {MenuContext} from "./menu";
import classNames from "classnames";
import {IMenuItemProps} from "./menuItem";
import Icon from "../Icon/icon";

import Transition from '../Transition/transition'


export interface ISubMenuProps {
  index?: string;  // 唯一编号
  title: string;
  className?: string;
}

const SubMenu: React.FC<ISubMenuProps> = (props) => {
  const {children, index, title, className} = props

  // 是否默认展开
  const [menuOpen, setOpen] = useState(false)

  const context = useContext(MenuContext)
  const classes = classNames("menu-item submenu-item", className, {
    "is-active": context.index === index,
    'is-vertical': context.mode === 'vertical', // 是否垂直
    'is-opened': menuOpen
  })

  const handleClick = (e: React.MouseEvent) => {
    e.preventDefault()
    setOpen(!menuOpen)
  }
  // 如果是垂直状态才有点击事件
  const clickEvents = context.mode === 'vertical' ? {
    onClick: handleClick
  } : {}


  let timer: any
  const handleMouse = (e: React.MouseEvent, toggle: boolean) => {
    clearTimeout(timer)
    e.preventDefault()
    timer = setTimeout(() => {
      setOpen(toggle)
    }, 200)
  }
  console.log(context.mode)
  const hoverEvents = context.mode === "horizontal" ? {
    onMouseEnter: (e: React.MouseEvent) => {
      handleMouse(e, true)
    },
    onMouseLeave: (e: React.MouseEvent) => {
      handleMouse(e, false)
    }
  } : {}

  // 渲染子菜单
  const renderChildren = () => {
    const subMenuClasses = classNames('viking-submenu', {
      'menu-opened': menuOpen,
    })
    const childrenComponent = React.Children.map(children, (child, i) => {
      const childElement = child as FunctionComponentElement<IMenuItemProps> // 转化成一个组件
      if (childElement.type.displayName === 'MenuItem') {
        return React.cloneElement(childElement, {
          index: `${index}-${i}`  // 因为需要唯一id,index要字符串。 例如：1-1
        })
      } else {
        console.error("Warning: SubMenu has a child which is not a MenuItem component")
      }
    })
    return (
      <Transition
        in={menuOpen}
        animation='zoom-in-top'
        timeout={300}>
        <ul className={subMenuClasses}>
          {childrenComponent}
        </ul>
      </Transition>
    )
  }

  return (
    <li key={index} className={classes} {...hoverEvents}>
      <div className='submenu-title' {...clickEvents}>
        {title}
        <Icon icon="angle-down" className="arrow-icon"/>
      </div>

      {renderChildren()}
    </li>
  )
}
SubMenu.displayName = 'SubMenu'
export default SubMenu
